package com.ykt.model;

import java.util.List;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.TableMapping;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import com.ykt.interceptor.Seach;

public abstract class CacheModel<M extends Model<M>> extends Model<M> {
	private static final long serialVersionUID = 1L;
	
	
	public Page<M> paginateCache(int pageNumber,int rows) {
        return this.paginateCache(pageNumber,rows, null);
    }
	public Page<M> paginateCache(int pageNumber,int rows,Seach seach) {
		String select="select id ";
		String sqlExceptSelect = " from "+getTableName()+" where 1=1 ";
		if(seach!=null){
			sqlExceptSelect+= seach.getSqlWhere();
			sqlExceptSelect+= seach.getOrderBy();
			return super.paginateByCache(getModelListCacheName(),getQueryKey(seach.getSqlParam())+"-"+pageNumber,pageNumber, 
					rows, select, sqlExceptSelect,seach.getSqlParam().toArray());
		}
        Page<M> bolgPage= paginateByCache(getModelListCacheName(),sqlExceptSelect+"-"+pageNumber,pageNumber, rows, select,
        		sqlExceptSelect);
        return loadModelPage(bolgPage);
    }
	
	
	public M loadModel(Object id) {
        final Object ID = id;
        return CacheKit.get(getModelCacheName(), ID, new IDataLoader() {
            @Override
            public M load() {
                return findById(ID);
            }
        });
    }
	public Page<M> loadModelPage(Page<M> page) {
        List<M> modelList = page.getList();
        loadModelList(modelList);
        return page;
    }
	public List<M> loadModelList(List<M> modelList) {
        for(int i = 0; i < modelList.size(); i++){
            Model<M> model = modelList.get(i);
            M topic = loadModel(model.get("id"));
            modelList.set(i, topic);
        }
        return modelList;
    }
	
	
	public void removeThisCache(Object id){
        CacheKit.remove(getModelCacheName(), id);
    }
    public void removeAllCache(){
        CacheKit.removeAll(getModelListCacheName());
    }
    private String getTableName(){
		return TableMapping.me().getTable(getClass()).getName();
	}
    private String getQueryKey(List<Object> list){
    	StringBuffer sb = new StringBuffer();
    	for(Object o : list){
    		sb.append(o.toString()+"-");
    	}
    	return sb.toString();
    }
    public abstract String getModelCacheName();
    
    public abstract String getModelListCacheName();
}
